package thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 线程池
 */
class MyThreadPool {
    //创建一个阻塞队列用来存放任务
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    //描述一个线程，这个线程的工作是从任务队列拿到任务执行
    static class Worker extends Thread{
        BlockingQueue<Runnable> queue = null;
        //构造方法拿到外面的任务队列
        public Worker(BlockingQueue queue) {
            this.queue = queue;
        }
        @Override
        public void run() {
            while (true) {
                try {
                    Runnable runnable = queue.take();  //如果为空会进入阻塞
                    runnable.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //创建一个链表结构存放线程
    private List<Thread> workers = new ArrayList<>();
    //构造方法确定所添加的核心线程数
    public MyThreadPool(int n) {
        for (int i = 0; i < n; i++) {
            Worker worker = new Worker(queue); //这是准备好了
            worker.start();   //只有进入了start线程才被创好
            workers.add(worker);  //添加到链表上
        }
    }
    //创建一个方法添加任务到队列中
    public void submit(Runnable runnable){
        try {
            queue.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class Demo12 {
    public static void main(String[] args) {
        MyThreadPool pool = new MyThreadPool(10);
        for (int i = 0; i < 20; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello,mythreadpool");
                }
            });
        }
    }
}
